package org.example.controller;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import org.example.common.R;
import org.example.domain.Menu;
import org.example.domain.MenuVO;
import org.example.domain.SysMenu;
import org.example.mapper.SysMenuMapper;
import org.example.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import javax.swing.event.MenuListener;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@Api(tags = {"菜单接口"})
@RequestMapping("menu")
public class SysMenuController {

    @Autowired
    MenuService menuService;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @RequestMapping("listDao")
    public List<Tree<String>> listDao(){

        List<Menu> menus = menuService.selectAllDao();

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

//        treeNodeConfig.setNameKey("label");
//        treeNodeConfig.setIdKey("value");


//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<Menu, String>build(menus, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getMenuId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
//                    tree.setWeight(treeNode.getWeight());
//                    tree.setName(treeNode.getMenuName());
                    // 扩展属性 ...
                    tree.putExtra("menuName", treeNode.getMenuName());
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("orderNum", treeNode.getOrderNum());
                    tree.putExtra("status", treeNode.getStatus());
                    tree.putExtra("createTime", treeNode.getCreateTime());
                    tree.putExtra("icon", treeNode.getIcon());
                    tree.putExtra("component", treeNode.getComponent());
                    tree.putExtra("perms", treeNode.getPerms());
                });



        return treeNodes;

    }

    @RequestMapping("list")
    public List<Tree<String>> list(@RequestBody(required = false) MenuVO menuVO) throws ParseException {
        List<Menu> menus = menuService.selectAll(menuVO);

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

//        treeNodeConfig.setNameKey("label");
//        treeNodeConfig.setIdKey("value");


//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<Menu, String>build(menus, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getMenuId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
//                    tree.setWeight(treeNode.getWeight());
//                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("menuName", treeNode.getMenuName());
                    tree.putExtra("orderNum", treeNode.getOrderNum());
                    tree.putExtra("status", treeNode.getStatus());
                    tree.putExtra("createTime", treeNode.getCreateTime());
                    tree.putExtra("icon", treeNode.getIcon());
                    tree.putExtra("component", treeNode.getComponent());
                    tree.putExtra("perms", treeNode.getPerms());
                });



        return treeNodes;
    }

    @RequestMapping("handleUpdate")
    public Map<String,Object> handleUpdate(Integer id){

        HashMap<String, Object> map = new HashMap<>();

        List<String> values = new ArrayList<>();
        values.add(0,id+"");

        Menu menu = menuService.selectByMenu(id);

        Integer parentId=menu.getParentId();

        int i=1;
        if (menu.getParentId()!=0){
            while (parentId!=0){
                Menu menu1 = menuService.selectByMenu(parentId);
                if (menu1==null){
                    break;
                }
                System.out.println(menu1);
                parentId=menu1.getParentId();
                System.out.println(parentId);
                values.add(i++,menu1.getMenuId()+"");
            }
        }

        Collections.reverse(values);
        map.put("data",menu);
        map.put("values",values);

        return map;
    }


    @RequestMapping("addMenu")
    public void addMenu(@RequestBody Menu menu){
        LocalDateTime localDateTime=LocalDateTime.now();
        menu.setCreateTime(localDateTime);
        System.out.println(menu);
        menuService.insertMenu(menu);

    }

    @RequestMapping("updateMenu")
    public void updateMenu(@RequestBody Menu menu){
        System.out.println(menu);
        menuService.updateMenu(menu);
    }


    @RequestMapping("handleDelete")
    public void handleDelete(Integer id){

        Integer parentId=menuService.selectById(id);

        if (parentId>10){
            menuService.deleteById(id);
            return;
        }

        if (parentId<=10 && parentId>=1){
            menuService.deleteByIdTwo(id);
            return;
        }

        Integer[] menuId=menuService.selectByParentId(id);
        System.out.println(menuId);


        for (int i = 0; i < menuId.length; i++) {
            menuService.deleteByIdTwo(menuId[i]);
        }

        //最后
        menuService.deleteById(id);


    }

    @RequestMapping("down")
    public void down(HttpServletResponse response) throws IOException {

        List<Menu> menus = menuService.selectAllDao();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("菜单列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Menu.class).sheet("模板").doWrite(menus);
    }

    @RequestMapping("upload")
    public void upload(MultipartFile file) throws IOException {
//        try {
////            EasyExcel.read(file.getInputStream(), Menu.class, new MenuListener(menuService)).sheet().doRead();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @RequestMapping("menuTree")
    public R menuTree() {
        List<SysMenu> menus = sysMenuMapper.menuList();

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
//        // 自定义属性名 都有默认值的
//        treeNodeConfig.setWeightKey("order");
//        treeNodeConfig.setIdKey("rid");
//        // 最大递归深度
//        treeNodeConfig.setDeep(3);
        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> menuTree = TreeUtil.<SysMenu, String>build(menus, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getMenuId() + "");
                    tree.setParentId(treeNode.getParentId() + "");
                    tree.setName(treeNode.getMenuName());
                });
        return R.successed(menuTree);
    }

}

